#!/usr/bin/env python3
"""
数据同步功能权限初始化脚本
创建同步相关的权限和路由配置
"""

import asyncio
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_

from app.core.database import AsyncSessionLocal
from app.models.auth import Permission, Route
from app.core.logger import logger


# 同步功能权限配置
SYNC_PERMISSIONS = [
    {
        'name': 'sync.view',
        'display_name': '查看同步功能',
        'description': '查看数据同步相关页面和信息',
        'resource': 'sync',
        'action': 'view'
    },
    {
        'name': 'sync:task:view',
        'display_name': '查看同步任务',
        'description': '查看数据同步任务列表和详情',
        'resource': 'sync_task',
        'action': 'view'
    },
    {
        'name': 'sync:task:create',
        'display_name': '创建同步任务',
        'description': '创建新的数据同步任务',
        'resource': 'sync_task',
        'action': 'create'
    },
    {
        'name': 'sync:task:update',
        'display_name': '更新同步任务',
        'description': '修改数据同步任务配置',
        'resource': 'sync_task',
        'action': 'update'
    },
    {
        'name': 'sync:task:delete',
        'display_name': '删除同步任务',
        'description': '删除数据同步任务',
        'resource': 'sync_task',
        'action': 'delete'
    },
    {
        'name': 'sync:task:execute',
        'display_name': '执行同步任务',
        'description': '手动执行数据同步任务',
        'resource': 'sync_task',
        'action': 'execute'
    },
    {
        'name': 'sync:execution:view',
        'display_name': '查看执行记录',
        'description': '查看数据同步执行记录和日志',
        'resource': 'sync_execution',
        'action': 'view'
    },
    {
        'name': 'sync:execution:control',
        'display_name': '控制执行过程',
        'description': '暂停、恢复、取消同步任务执行',
        'resource': 'sync_execution',
        'action': 'control'
    },
    {
        'name': 'sync:config:manage',
        'display_name': '管理同步配置',
        'description': '管理数据同步相关配置',
        'resource': 'sync_config',
        'action': 'manage'
    },

]

# 同步功能路由配置
SYNC_ROUTES = [
    {
        'path': '/sync',
        'name': 'sync',
        'display_name': '数据同步',
        'description': '数据同步管理功能',
        'icon': 'SyncOutlined',
        'component': 'SyncManagement',
        'is_menu': True,
        'sort_order': 5,
        'permissions': ['sync.view'],
        'children': [
            {
                'path': '/sync/tasks',
                'name': 'sync_tasks',
                'display_name': '同步任务',
                'description': '数据同步任务管理',
                'icon': 'ScheduleOutlined',
                'component': 'SyncTaskManagement',
                'is_menu': True,
                'sort_order': 1,
                'permissions': ['sync:task:view']
            },
            {
                'path': '/sync/executions',
                'name': 'sync_executions',
                'display_name': '执行记录',
                'description': '同步任务执行记录',
                'icon': 'HistoryOutlined',
                'component': 'SyncExecutionMonitor',
                'is_menu': True,
                'sort_order': 2,
                'permissions': ['sync:execution:view']
            },

        ]
    }
]


async def create_permissions(db: AsyncSession):
    """创建同步功能权限"""
    logger.info("开始创建同步功能权限...")
    
    created_count = 0
    updated_count = 0
    
    for perm_config in SYNC_PERMISSIONS:
        # 检查权限是否已存在
        existing_perm = await db.execute(
            select(Permission).where(Permission.name == perm_config['name'])
        )
        existing_perm = existing_perm.scalar_one_or_none()
        
        if existing_perm:
            # 更新现有权限
            existing_perm.display_name = perm_config['display_name']
            existing_perm.description = perm_config['description']
            existing_perm.resource = perm_config['resource']
            existing_perm.action = perm_config['action']
            updated_count += 1
            logger.info(f"更新权限: {perm_config['name']}")
        else:
            # 创建新权限
            permission = Permission(
                name=perm_config['name'],
                display_name=perm_config['display_name'],
                description=perm_config['description'],
                resource=perm_config['resource'],
                action=perm_config['action']
            )
            db.add(permission)
            created_count += 1
            logger.info(f"创建权限: {perm_config['name']}")
    
    await db.commit()
    logger.info(f"权限创建完成: 新建 {created_count} 个，更新 {updated_count} 个")


async def create_routes(db: AsyncSession, parent_route=None, routes_config=None):
    """递归创建路由"""
    if routes_config is None:
        routes_config = SYNC_ROUTES
    
    for route_config in routes_config:
        # 检查路由是否已存在
        existing_route = await db.execute(
            select(Route).where(Route.path == route_config['path'])
        )
        existing_route = existing_route.scalar_one_or_none()
        
        if existing_route:
            # 更新现有路由
            existing_route.name = route_config['name']
            existing_route.display_name = route_config['display_name']
            existing_route.description = route_config['description']
            existing_route.icon = route_config.get('icon')
            existing_route.component = route_config.get('component')
            existing_route.is_menu = route_config.get('is_menu', True)
            existing_route.sort_order = route_config.get('sort_order', 0)
            existing_route.parent_id = parent_route.id if parent_route else None
            logger.info(f"更新路由: {route_config['path']}")
            current_route = existing_route
        else:
            # 创建新路由
            route = Route(
                path=route_config['path'],
                name=route_config['name'],
                display_name=route_config['display_name'],
                description=route_config['description'],
                icon=route_config.get('icon'),
                component=route_config.get('component'),
                parent_id=parent_route.id if parent_route else None,
                sort_order=route_config.get('sort_order', 0),
                is_menu=route_config.get('is_menu', True),
                is_active=True,
                is_system=True
            )
            db.add(route)
            await db.flush()  # 获取路由ID
            logger.info(f"创建路由: {route_config['path']}")
            current_route = route
        
        # 递归创建子路由
        if 'children' in route_config:
            await create_routes(db, current_route, route_config['children'])


async def init_sync_permissions():
    """初始化同步功能权限和路由"""
    try:
        logger.info("开始初始化数据同步功能权限和路由...")
        
        async with AsyncSessionLocal() as db:
            # 创建权限
            await create_permissions(db)
            
            # 创建路由
            await create_routes(db)
            
            await db.commit()
        
        logger.info("数据同步功能权限和路由初始化完成！")
        
    except Exception as e:
        logger.error(f"初始化失败: {e}")
        raise


async def main():
    """主函数"""
    try:
        await init_sync_permissions()
        print("✅ 数据同步功能权限和路由初始化成功！")
    except Exception as e:
        print(f"❌ 初始化失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    asyncio.run(main())
